package pers.cyril.jdb.storage.api.spi;

import pers.cyril.jdb.storage.api.annotation.StorageEngine;

import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 说点什么吧
 *
 * @author Wang Cyril
 * @date 2024/5/21 22:30
 */
public class StorageEngineLocator {

    private static final Map<String, Object> serviceCache = new ConcurrentHashMap<>();

    public static <T> T findEngineClass(String storageEngine, Class<T> clazz) {
        Object obj = serviceCache.get(String.format("%s:%s", storageEngine, clazz.getName()));
        if (obj != null) {
            return (T) obj;
        }
        ServiceLoader<T> serviceLoader = ServiceLoader.load(clazz);
        Iterator<T> iterator = serviceLoader.iterator();
        while (iterator.hasNext()) {
            obj = iterator.next();
            Class<?> rawClass = obj.getClass();
            StorageEngine annotation = rawClass.getAnnotation(StorageEngine.class);
            if (annotation != null && storageEngine.equals(annotation.name())) {
                serviceCache.put(String.format("%s:%s", storageEngine, clazz.getName()), obj);
                return (T) obj;
            }
        }
        return null;
    }
}
